package org.spindle.soasuite.parser.json;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.spindle.soasuite.parser.api.IParser;
import org.spindle.soasuite.parser.api.ParserConstants;

import java.io.IOException;

public class JSONParser implements IParser {

    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public Object unmarshallString(String data) {
        JsonNode rootNode = null;

        try {
            rootNode = mapper.readTree(data);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return rootNode;
    }

    @Override
    public String marshallData(Object dataObject) {
        String result = null;

        try {
            result = mapper.writeValueAsString(dataObject);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public String getStringValueByPath(Object dataObject, String path) {

        int indexOfDot = path.indexOf(".");
        JsonNode rootNode = null;
        String resultObject = null;
        String key;
        String resultPath;

        if (dataObject instanceof JsonNode) {
            rootNode = (JsonNode) dataObject;
            if (indexOfDot != -1) {
                key = path.substring(0, indexOfDot);
                resultPath = path.substring(indexOfDot + 1);
                resultObject = getStringValueByPath(rootNode.path(key), resultPath);
            } else {
                resultObject = rootNode.path(path).getValueAsText();
            }
        }
        return resultObject;
    }

    public JsonNode getObjectByPath(Object dataObject, String path) {
        int indexOfDot = path.indexOf(".");
        JsonNode rootNode = null;
        JsonNode resultObject = null;
        String key;
        String resultPath;

        if (dataObject instanceof JsonNode) {
            rootNode = (JsonNode) dataObject;
            if (indexOfDot != -1) {
                key = path.substring(0, indexOfDot);
                resultPath = path.substring(indexOfDot + 1);
                resultObject = getObjectByPath(rootNode.path(key), resultPath);
            } else {
                resultObject = rootNode.path(path);
            }
        }
        return resultObject;
    }

    @Override
    public int parserType() {
        return ParserConstants.JSON_PARSER_TYPE;
    }

}
